# 自定义过滤器  1> 参数接收模板变量  2> 将转换结果返回
import functools

from flask import session, current_app, g

from info.models import User


def func_index_convert(index):  # index = 4

    index_dict = {1: "first", 2: "second", 3: "third"}

    return index_dict.get(index, "")


# 获取用户登录信息
def user_login_data(f):  # f = news_detail

    @functools.wraps(f)  # 可以让被装饰的函数wrapper使用指定函数f的信息(如函数名, 函数注释)
    def wrapper(*args, **kwargs):
        # 判断用户是否登录
        user_id = session.get("user_id")
        user = None  # type: User
        if user_id:  # 用户已登录
            # 查询出用户数据
            try:
                user = User.query.get(user_id)
            except BaseException as e:
                current_app.logger.error(e)

        g.user = user
        # print(wrapper.__name__)  # 获取函数名

        return f(*args, **kwargs)

    return wrapper


# 文件上传
def file_upload(data):
    """
    文件上传
    :param data: 上传的内容
    :return: 文件名
    """
    import qiniu
    access_key = "kJ8wVO7lmFGsdvtI5M7eQDEJ1eT3Vrygb4SmR00E"
    secret_key = "rGwHyAvnlLK7rU4htRpNYzpuz0OHJKzX2O1LWTNl"
    bucket_name = "infonews"

    q = qiniu.Auth(access_key, secret_key)
    key = None  # 设置文件名, 设置None会生成随机名称
    token = q.upload_token(bucket_name)
    ret, info = qiniu.put_data(token, key, data)

    if ret is not None:  # 上传成功, 返回文件名

        return ret.get("key")  # 获取随机文件名

    else:  # 上传失败
        raise BaseException(info)
